/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    function: 裁剪图片的脚本
    contact:dcdev_founder@foxmail.com
*/
(function (window, undefined) {
    if (!document.getElementById(`_dc_crop_image_container_`)) {
        function _dc_crop_image_set_center_(id) {
            if (browser_info.is_mobile) {
                return;
            }
            $(`#${id}`)
                .css("top", (browser_info.height - $(`#${id}`).height()) / 2)
                .css("left", (browser_info.width - $(`#${id}`).width()) / 2);
        }

        var html = `
<div id="_dc_crop_image_mask_" class="_dcdev_preset_"
    style="z-index:99999;position:fixed;top:0;left:0;width:100%;height:100%;background-color:black;opacity:0.8;display:block;">
</div>
<div id="_dc_crop_image_container_"
    style="display:-webkit-inline-box;position:absolute;z-index:999999;left:10px;top:10px;background-color:white;">
    <div id="_dc_crop_image_viewer" style="border:1px solid #ddd;margin:10px;">
        <img id="_dc_crop_image_viewer_img_" />
    </div>

    <div id="_dc_crop_image_func_container__" style="margin-right:10px;">
        <div id="_dc_crop_image_func_container_"
            style="text-align:center;display:-webkit-inline-box;margin-top:10px;">
            <div style="text-align:center;">
                <div id="_dc_crop_image_preview_" class="circular previewImg" style="display:none;margin-left: 10px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            border: 1px solid lightgray;"></div>
            </div>
            <div id="_dc_crop_image_func_size_">
                <ul>
                    <li id="_dc_crop_image_func_panel_mobile_" style="display:none"></li>
                    <li style="display:-webkit-box;width:100%;padding:10px 0px 0px 10px">
                        <div class="dcdev-title">图片大小</div>
                        <input style="width:100px" id="_dc_crop_image_w_" readonly="readonly"> <span style="padding: 10px;vertical-align: -webkit-baseline-middle;">×</span> <input style="width:100px" id="_dc_crop_image_h_" readonly="readonly">
                    </li>
                    <li style="display:-webkit-box;width:100%;padding:0px 0px 0px 10px">
                        <div class="dcdev-title">裁剪大小</div>

                        <input type="number"  style="width:100px" id="_dc_crop_image2_w_"> <span style="padding: 10px;vertical-align: -webkit-baseline-middle;">×</span> <input type="number" style="width:100px" id="_dc_crop_image2_h_">
                    </li>
                </ul>
            </div>
            <div id="_dc_crop_image_func_panel_" style="text-align:center;">
                
            <div class="layui-form">
            <input type="radio" lay-filter="image_ratio" name="image_ratio" value="" title="不限" checked>
            <input type="radio" lay-filter="image_ratio" name="image_ratio" value="1:1" title="1 : 1" >
            <input type="radio" lay-filter="image_ratio" name="image_ratio" value="4:3" title="4 : 3" >
            <input type="radio" lay-filter="image_ratio" name="image_ratio" value="16:9" title="16 : 9" >
        </div>
        <div id="_dc_crop_image_select_"
        style="margin-top:10px;margin-bottom:10px;text-align:center;font-size:12px;">选择图片</div>
    <input id="open_file_selector" type="file" style="display:none;">
    <div style="width:100%;text-align:center;">
        <a id="_dc_crop_image_scaleX_" style="margin-left: 10px;font-size:12px;">水平反转</a>
        <a id="_dc_crop_image_scaleY_" style="margin-left: 10px;font-size:12px;">上下反转</a>
        <a id="_dc_crop_image_rotate_left_" style="margin-left: 10px;font-size:12px;">向左旋转</a>
        <a id="_dc_crop_image_rotate_right_" style="margin-left: 10px;font-size:12px;">向右旋转</a>
    </div>
            </div>
        </div>
        <div id="_dc_crop_image_button_panel_" style="width:100%;text-align:right;margin-top: 10px;">
            <div id="_dc_crop_image_info_"></div>
            <button id="_dc_crop_image_confirm_">确定</button><button id="_dc_crop_image_cancel_"
                style="margin:10px;margin-top: 2px;">取消</button>
        </div>
    </div>
</div>
`
        $(`body`).append(html);
        // $("#_dc_crop_image2_w_").bind('input', function () {
        //     editCropperSize()
        // })
        // $("#_dc_crop_image2_h_").bind('input', function () {
        //     editCropperSize()
        // })
        function editCropperSize() {
            crop_image.crop({ "aspectRatio": $("#_dc_crop_image2_w_").val() + "/" + $("#_dc_crop_image2_h_").val() })
            // $('#_dc_crop_image_viewer_img_').cropper("setData", { "aspectRatio": $("#_dc_crop_image2_w_").val() + "/" + $("#_dc_crop_image2_h_").val() });
        }
        // 移动版横屏
        function mobile_lanscape() {
            $(`#_dc_crop_image_preview_`).css("width", 80).css("height", 80).css("margin", 0);
            $(`#_dc_crop_image_func_container_`).css("display", "display:-webkit-inline-box;").css("text-align", "center");
            $(`#_dc_crop_image_viewer`).css("height", browser_info.height - 40 + "px");
            $(`#_dc_crop_image_viewer`).css("width", browser_info.height - 40 + "px");
            $(".preview-box-parcel").css("position", "absolute").css("top", "40px").css("right", "30px")
        }
        // 移动版竖屏
        function mobile_portrait() {
            $(`#_dc_crop_image_container_`).css("display", "").css("width", browser_info.width - 20);
            $(`#_dc_crop_image_viewer`).css("height", browser_info.width * 3 / 4 + "px");
            $(`#_dc_crop_image_func_panel_mobile_`).css("width", browser_info.width - 20 + "px");
            $(`#_dc_crop_image_select_`).css("margin-top", 0).css("margin-bottom", 6);
            $(`#_dc_crop_image_func_container__`).css("margin-right", 0);
        }

        // 移动端
        if (browser_info.is_mobile) {
            // 竖屏
            if (browser_info.width < browser_info.height) {
                mobile_portrait();
            }
            // 横屏
            else {
                mobile_lanscape();
            }
            $("#_dc_crop_image_func_panel_mobile_").show().html(`
            <div class="layui-form">
                <input type="radio" lay-filter="image_ratio" name="image_ratio" value="" title="不限" checked>
                <input type="radio" lay-filter="image_ratio" name="image_ratio" value="1:1" title="1 : 1" >
                <input type="radio" lay-filter="image_ratio" name="image_ratio" value="4:3" title="4 : 3" >
                <input type="radio" lay-filter="image_ratio" name="image_ratio" value="16:9" title="16 : 9" >
            </div>
            <div id="_dc_crop_image_select_"
            style="margin-top:10px;margin-bottom:10px;text-align:center;font-size:12px;">选择图片</div>
        <input id="open_file_selector" type="file" style="display:none;">
        <div style="width:100%;text-align:center;">
            <a id="_dc_crop_image_scaleX_" style="margin-left: 10px;font-size:12px;">水平反转</a>
            <a id="_dc_crop_image_scaleY_" style="margin-left: 10px;font-size:12px;">上下反转</a>
            <a id="_dc_crop_image_rotate_left_" style="margin-left: 10px;font-size:12px;">向左旋转</a>
            <a id="_dc_crop_image_rotate_right_" style="margin-left: 10px;font-size:12px;">向右旋转</a>
        </div>`)
            $("#_dc_crop_image_func_panel_").remove()
            $("#_dc_crop_image_w_").css("width", "60px")
            $("#_dc_crop_image_h_").css("width", "60px")
            $("#_dc_crop_image2_w_").css("width", "60px")
            $("#_dc_crop_image2_h_").css("width", "60px")
        }
        // 桌面端
        else {
            $(`#_dc_crop_image_preview_`).css("width", '80px').css("height", '80px').css("margin", '0px auto');
            $(`#_dc_crop_image_func_container_`).css("display", "").css("text-align", "center");
            $(`#_dc_crop_image_viewer`).css("height", 500 + "px");
            $(`#_dc_crop_image_viewer`).css("width", 500 + "px");
            $(".preview-box-parcel").css("position", "absolute").css("top", "40px").css("right", "30px")
        }
        $(`#_dc_crop_image_cancel_`).click(function () {
            $(`#_dc_crop_image_mask_`).css("display", "none");
            $(`#_dc_crop_image_container_`).css("display", "none");
        })
        // 设置屏幕居中
        _dc_crop_image_set_center_("_dc_crop_image_container_");
    }
    else {
        $(`#_dc_crop_image_mask_`).css("display", "block");
        $(`#_dc_crop_image_container_`).css("display", "block");
    }

    //图片
    $(`#_dc_crop_image_select_`).click(function () {
        $("#open_file_selector").click();
    });
    //左旋转
    $(`#_dc_crop_image_rotate_left_`).click(function () {
        $('#_dc_crop_image_viewer_img_').cropper("rotate", 45);
    });
    //右旋转
    $(`#_dc_crop_image_rotate_right_`).click(function () {
        $('#_dc_crop_image_viewer_img_').cropper("rotate", -45);
    });
    //水平反转
    var flagX = true;
    $(`#_dc_crop_image_scaleX_`).click(function () {
        if (flagX) {
            $('#_dc_crop_image_viewer_img_').cropper("scaleX", -1);
            flagX = false;
        } else {
            $('#_dc_crop_image_viewer_img_').cropper("scaleX", 1);
            flagX = true;
        }
        flagX != flagX;
    });
    //上下反转
    var flagY = true;
    $(`#_dc_crop_image_scaleY_`).click(function () {
        if (flagY) {
            $('#_dc_crop_image_viewer_img_').cropper("scaleY", -1);
            flagY = false;
        } else {
            $('#_dc_crop_image_viewer_img_').cropper("scaleY", 1);
            flagY = true;
        }
        flagY != flagY;
    });
    $("#open_file_selector").bind('change', function () {
        selectImg(this);
    })
    var imgwidth;
    var imgheight;
    var img_max_width;
    var img_max_width2;
    var img_max_height;
    var img_max_height2;
    var cropperSet;
    var cropped_ratio = "";
    var cropped_ratio_choose = false;
    crop_image = {
        // 显示loading
        crop: function (data, cb) {
            layui.use(['form'], function () {
                form = layui.form;
                form.render();
            })
            img_max_height = data.maxheight
            img_max_width = data.maxwidth
            window["_dc_crop_image_data_"] = data;
            window["_dc_crop_image_cb_"] = cb;
            data.preview = '.previewImg'  //预览视图
            data.cropmove = function (e) {
                if (img_max_width2 >= img_max_width) {
                    $('#_dc_crop_image_viewer_img_').cropper('setCropBoxData', { width: img_max_width, height: img_max_height })
                }
                var a = $('#_dc_crop_image_viewer_img_').cropper('getData', true);
                $(`#_dc_crop_image_preview_`).css("width", '160px').css("height", '80px').css("margin", '0px auto');
            };
            data.cropend = function (e) {
                if (img_max_width2 >= img_max_width) {
                    $('#_dc_crop_image_viewer_img_').cropper('setCropBoxData', { width: img_max_width, height: img_max_width })
                }
                $(`#_dc_crop_image_preview_`).css("width", '80px').css("height", '80px').css("margin", '0px auto');
            };
            data.crop = function (e) {
                var width;
                var height;
                if ($('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',).width >= img_max_width) {
                    width = img_max_width
                } else {
                    width = parseInt($('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',).width)
                }
                if ($('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',).height >= img_max_height) {
                    height = img_max_height
                } else {
                    height = parseInt($('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',).height)
                }
                $("#_dc_crop_image2_w_").val(width)
                $("#_dc_crop_image2_h_").val(height)
                img_max_width2 = width
                img_max_height2 = height

                //监听比例选项
                form.on("radio(image_ratio)", function (obj) {
                    cropped_ratio = obj.value;
                    if (obj.value != "") {
                        cropped_ratio_choose = true
                        img_max_height2 = img_max_width2 / obj.value.split(':')[0] * obj.value.split(':')[1]
                        $("#_dc_crop_image2_h_").val(img_max_height2)
                        console.log($('#_dc_crop_image_viewer_img_').cropper("setAspectRatio",""))
                        console.log($('#_dc_crop_image_viewer_img_').cropper("aspectRatio",""))
                        console.log($('#_dc_crop_image_viewer_img_').cropper("getData",""))
                        console.log($('#_dc_crop_image_viewer_img_').cropper("getData",true))
                        $('#_dc_crop_image_viewer_img_').cropper({ "setAspectRatio": cropped_ratio })
                        $('#_dc_crop_image_viewer_img_').cropper('setCropBoxData', { "left": (img_max_width - img_max_width2) / 2, "top": (img_max_height - img_max_height2) / 2, "width": img_max_width2, "height": img_max_height2 })
                    } else {
                        cropped_ratio_choose = false
                    }
                })
            };
            cropperSet = data;
            //cropper图片裁剪
            $('#_dc_crop_image_viewer_img_').cropper(cropperSet);
            // 是否自动选择图片
            if (window["_dc_crop_image_data_"].autoSelectImg) {
                $(`#_dc_crop_image_select_`).click()
            }
        },
    }
    $("#_dc_crop_image_viewer_img_").on("click", function () {
        console.log($('#_dc_crop_image_viewer_img_').cropper('getData', true));;
    })

    $("#_dc_crop_image_confirm_").click(function () {
        var cropped_canvas = parent.$('#_dc_crop_image_viewer_img_').cropper('getCroppedCanvas', { width: 222, height: 222 }); //获取被裁剪后的canvas
        var cropped_data = cropped_canvas.toDataURL('image/jpeg');
        if (window["_dc_crop_image_cb_"]) {
            var res = {
                image_info: $('#_dc_crop_image_viewer_img_').cropper('getImageData',),
                cropped_info: $('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',),
                cropped_data: cropped_data,
                cropped_ratio: cropped_ratio,
            }
            // console.log($('#_dc_crop_image_viewer_img_').cropper('getImageData',));
            // console.log($('#_dc_crop_image_viewer_img_').cropper('getCropBoxData',));
            // console.log(cropped_data)
            window["_dc_crop_image_cb_"](res)
        }
    })
    function selectImg(file) {
        if (!file.files || !file.files[0]) {
            return;
        }
        var reader = new FileReader();
        reader.onload = function (evt) {
            var replaceSrc = evt.target.result;
            //更换cropper的图片
            $('#_dc_crop_image_viewer_img_').cropper('replace', replaceSrc, false); //默认false，适应高度，不失真            
            var img = new Image();
            img.src = replaceSrc;
            img.onload = function () {
                imgwidth = img.width
                imgheight = img.height
                $("#_dc_crop_image_w_").val(imgwidth)
                $("#_dc_crop_image_h_").val(imgheight)
            };
        }
        reader.readAsDataURL(file.files[0]);
        // setTimeout(() => {
        //     if (window["_dc_crop_image_data_"].imageInfo) {
        //         var a = $('#_dc_crop_image_viewer_img_').cropper('getImageData',);
        //         $(`#_dc_crop_image_info_`).html(`${a.naturalWidth} * ${a.naturalHeight} scale: ${a.scaleX}`)
        //     } else {
        //         $(`#_dc_crop_image_preview_`).css("width", '80px').css("height", '80px').css("margin", '0px auto');
        //     }
        // }, 100);
    }



    //监听手机屏幕因旋转或进入文本框之后的变化
    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function () {
        // 横屏
        if (window.orientation == 90 || window.orientation == 270) {
            mobile_lanscape();
        }
        // 竖屏
        else {
            mobile_portrait();
        }
    }, false);
    function returnResult(data, callback) {
        return callback(data);
    }
})(window);
